package io.wdb.wxapp.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;

import io.wdb.common.utils.CommonUtil;
import io.wdb.common.utils.SignUtil;
import io.wdb.wxapp.util.PayCommonUtil;
import io.wdb.wxapp.util.WxAppPayUtil;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("wxapp")
public class WxAppUserController {
	private static Logger logger = LoggerFactory.getLogger(WxAppUserController.class);
	
	@Value(value = "${wxapp.appid}")
	public String appid;
	@Value(value = "${wxapp.secret}")
	public String secret;
	
	@Value(value = "${wxapp.token}")
	public String token;
	
	@Value(value = "${wxapp.merchant_id}")
	public String merchant_id;
	
	@Value(value = "${wxapp.merchant_key}")
	public String merchant_key;
	
	@Value(value = "${wxapp.notify_url}")
	public String notify_url;
	
	//登录
	@RequestMapping("login")
	@ResponseBody
	public Object login(HttpServletRequest request) {
		
		 Map<String, Object> result = new HashMap<>();
		 result.put("status", 0);
		return result;
	}
	
	/**
	 * 微信消息验证接口
	 * @param request
	 * @return
	 */
	@RequestMapping("checksign")
	@ResponseBody
	public Object index(HttpServletRequest request) {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		logger.info("微信校验:{} {} {} {}",signature, timestamp, nonce, echostr);
		if(echostr != null) return echostr;
		if (SignUtil.checkSignature(token, signature, timestamp, nonce)) {
			logger.info("微信check true");
//			return echostr;
		}
		return echostr;
	}
	
	/**
	 * 根据code获取openid
	 * @param code
	 * @return
	 */
	@GetMapping("openid")
	@ResponseBody
    public String login(String code) {
        if (StringUtils.isEmpty(code)) {
            return "empty jscode";
        }
        try {
        	String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        	requestUrl = requestUrl.replace("APPID", appid).replace("SECRET", secret).replace("JSCODE", code);
        	logger.info("初始requestUrl:{}",requestUrl);
        	JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        	logger.info("userinfo json:{}", jsonObject);
        	return jsonObject.toString();
        } catch (Exception e) {
        	
            logger.error(e.getMessage(), e);
            return e.toString();
        }
    }
	
	/**
	 * 统一支付订单
	 * @param openid
	 * @return
	 */
	@RequestMapping("payment")
	@ResponseBody
    public Object payment(HttpServletRequest request) {
		String openid = request.getParameter("openid");
		String total_fee = request.getParameter("chargeamount");
		logger.info("openid：{},创建支付{}",openid,total_fee);
        if (StringUtils.isEmpty(openid)) {
            return "empty openid";
        }
        Map<String, Object> result = new HashMap<>();
        try {

        	String timeStamp = PayCommonUtil.create_timestamp();
    		String nonceStr = PayCommonUtil.create_nonce_str();
    		
    		String orderNo = System.currentTimeMillis()+"";
    		result.put("appid", appid);
    		result.put("timestamp", timeStamp);
    		result.put("nonceStr", nonceStr);
        	result.put("openid", openid);
        	result.put("orderNo", orderNo);
        	String prepayId = WxAppPayUtil.unifiedorder("微信小程序押金测试", orderNo, openid, total_fee,
        			appid, merchant_id, notify_url, merchant_key);
        	//TODO 调起统一支付接口
        	logger.info("openid:{},统一下单返回:{}",openid,prepayId);
        	

    		SortedMap<Object, Object> signParams = new TreeMap<Object, Object>();
    		signParams.put("appId", appid);
    		signParams.put("nonceStr", nonceStr);
    		signParams.put("package", "prepay_id=" + prepayId);
    		signParams.put("timeStamp", timeStamp);
    		signParams.put("signType", "MD5");

    		// 生成支付签名，要采用URLENCODER的原始值进行SHA1算法！
    		String sign = PayCommonUtil.createSign(signParams, merchant_key);
        	
    		result.put("paySign", sign);
    		result.put("packageValue", "prepay_id=" + prepayId);
        	
        	return result;
        } catch (Exception e) {
        	
            logger.error(e.getMessage(), e);
            return e.toString();
        }
    }
	
}
